<template>
  <div class="app-container">
<!--    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="楼宇名称" prop="userBuildingId">
      <el-select
       v-model="queryParams.userBuildingId"
     placeholder="请选择楼宇"
         clearable
         @change="handleQuery"
        >
         <el-option
            v-for="building in buildingList"
            :key="building.id"
           :label="building.buildingName"
           :value="building.id"
         />
        </el-select>
      </el-form-item>
      <el-form-item label="房屋ID" prop="userRoomId">
        <el-input
          v-model="queryParams.userRoomId"
         placeholder="请输入房屋ID"
         clearable
          @keyup.enter="handleQuery"
        />
     </el-form-item>
     <el-form-item label="用户车牌" prop="userCarCode">
        <el-input
          v-model="queryParams.userCarCode"
          placeholder="请输入用户车牌"
         clearable
         @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>-->

<!--    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
         type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['auditUserDetail:reviewUserDetail:addSelf']"
       >申请审核</el-button>
     </el-col>
      <el-col :span="1.5">
       <el-button
          type="success"
         plain
        icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['myUserDetail:myRoomAndCar:edit']"
        >修改</el-button>
      </el-col>
     <el-col :span="1.5">
        <el-button
          type="danger"
         plain
         icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['myUserDetail:myRoomAndCar:remove']"
       >删除</el-button>
      </el-col>
      <el-col :span="1.5">
      <el-button
         type="warning"
          plain
         icon="Download"
          @click="handleExport"
         v-hasPermi="['myUserDetail:myRoomAndCar:export']"
        >导出</el-button>
     </el-col>
     <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

<!--    <div style="margin-bottom: 10px;">数据长度: {{ myRoomAndCarList.length }}, 数据内容: {{ myRoomAndCarList }}</div>-->
    
    <!-- 有数据时显示表格 -->
    <div v-if="myRoomAndCarList.length > 0">
      <el-table v-loading="loading" :data="myRoomAndCarList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="业主姓名" align="center" prop="userName" />
<!--        <el-table-column label="主键ID" align="center" prop="id" />-->
        <el-table-column label="楼宇名称" align="center">
          <template #default="scope">
            {{ getBuildingName(scope.row.userBuildingId) }}
          </template>
        </el-table-column>
        <el-table-column label="房间号" align="center">
          <template #default="scope">
            {{ getRoomNo(scope.row.userRoomId) }}
          </template>
        </el-table-column>
        <el-table-column label="用户车牌" align="center" prop="userCarCode" />
<!--      <el-table-column label="特征数据" align="center" prop="userFaceFeature" />-->
<!--      <el-table-column label="业主照片地址" align="center" prop="faceImageUrl" />-->
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
         <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['myUserDetail:myRoomAndCar:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['myUserDetail:myRoomAndCar:remove']">删除</el-button>
        </template>
      </el-table-column>-->
      </el-table>
    </div>
    
    <!-- 有未通过的申请时显示提示 -->
    <div v-else-if="!loading && hasPendingReview" style="text-align: center; padding: 40px 0">
      <div style="color: #606266; font-size: 16px; margin-bottom: 20px;">
        你的申请已提交，请耐心等待审核结果
      </div>
    </div>
    
    <!-- 既没有数据也没有未通过的申请时显示去绑定信息 -->
    <div v-else-if="!loading" style="text-align: center; padding: 40px 0">
<!--      <div v-if="checkPermi(['auditUserDetail:reviewUserDetail:addSelf'])" style="text-align: center;">-->
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          class="empty-state-button"
        >去绑定我的房屋信息</el-button>
      </div>
<!--      <div v-else>-->
<!--        暂无数据-->
<!--      </div>-->
<!--    </div>-->
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改我的车房对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="myRoomAndCarRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼宇名称" prop="userBuildingId">
          <el-select v-model="form.userBuildingId" placeholder="请选择楼宇" @change="handleBuildingChange">
            <el-option
              v-for="building in buildingList"
              :key="building.id"
              :label="building.buildingName"
              :value="building.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="userRoomNo">
          <el-select v-model="form.userRoomNo" placeholder="请选择房间号" :disabled="!form.userBuildingId">
            <el-option
              v-for="room in filteredRoomList"
              :key="room.id"
              :label="room.roomNo"
              :value="room.roomNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户车牌" prop="userCarCode">
          <el-input v-model="form.userCarCode" placeholder="请输入用户车牌" />
        </el-form-item>
<!--        <el-form-item label="特征数据" prop="userFaceFeature">-->
<!--          <el-input v-model="form.userFaceFeature" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="业主照片地址" prop="faceImageUrl">-->
<!--          <el-input v-model="form.faceImageUrl" placeholder="请输入业主照片地址" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="submitButtonDisabled">{{ submitButtonText }}</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MyRoomAndCar">
import { listMyRoomAndCar, getMyRoomAndCar, delMyRoomAndCar, updateMyRoomAndCar } from "@/api/myUserDetail/myRoomAndCar"
import { addSelfReview, checkUserPendingReview } from "@/api/auditUserDetail/reviewUserDetail"
import { listBuildingManage } from "@/api/behindBuilding/buildingManage"
import { listRoomManage, getUnbindRoomsByBuildingId } from "@/api/behindRoom/roomManage"
import { getUserNameByUserDetailId } from "@/api/userDetail/privateUserDetail"
import { ref, reactive, computed, h, onMounted, getCurrentInstance } from "vue"
import { checkPermi } from "@/utils/permission"

const { proxy } = getCurrentInstance()

const myRoomAndCarList = ref([])
const buildingList = ref([])
const buildingMap = ref(new Map())
const roomList = ref([]) // 所有房间列表
const filteredRoomList = ref([]) // 当前楼宇下的房间列表
const roomNoToIdMap = ref(new Map())
const roomIdToNoMap = ref(new Map()) // 房间ID到房间号的映射
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const hasPendingReview = ref(false) // 是否有未通过的申请
const submitButtonDisabled = ref(false) // 提交按钮禁用状态
const submitButtonText = ref("确 定") // 提交按钮文字

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userBuildingId: null,
    userRoomId: null,
    userCarCode: null,
  },

  rules: {
      userBuildingId: [
        { required: true, message: "楼宇名称不能为空", trigger: "change" }
      ],
      userRoomNo: [
        { required: true, message: "房间号不能为空", trigger: "change" },
        {
          validator: (rule, value, callback) => {
            if (!form.value.userBuildingId) {
              callback(new Error('请先选择楼宇名称'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ]
    }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询我的车房列表 */
function getList() {
  loading.value = true
  listMyRoomAndCar(queryParams.value).then(async response => {
    console.log('车房列表原始数据:', response.rows)
    
    // 获取车房列表
    const roomAndCarList = response.rows
    
    // 为每个车房记录添加业主姓名
    const updatedList = await Promise.all(
      roomAndCarList.map(async item => {
        try {
          // 首先尝试使用userDetailId字段，如果不存在则使用id字段
          const userIdToUse = item.userDetailId || item.id
          // 调用接口获取业主姓名
          const nameResponse = await getUserNameByUserDetailId(userIdToUse)
          if (nameResponse.code === 200 && nameResponse.msg) {
            return { ...item, userName: nameResponse.msg }
          }
        } catch (error) {
          console.error('获取业主姓名失败:', error)
        }
        return { ...item, userName: '未获取到姓名' }
      })
    )
    myRoomAndCarList.value = updatedList
    total.value = response.total
    loading.value = false
  })
}



/** 检查是否有未通过的申请 */
async function checkUserReviewStatus() {
  try {
    // 使用全新的API函数，彻底避免函数引用问题
    const result = await checkUserPendingReview()
    console.log('审核申请检查结果:', result)
    // 增强逻辑，确保能够正确识别审核状态
    if (result && result.code === 200 && (result.total > 0 || result.data?.total > 0 || result.data > 0)) {
      hasPendingReview.value = true
      console.log('有未通过的申请，设置hasPendingReview为true')
    } else {
      hasPendingReview.value = false
      console.log('没有未通过的申请，设置hasPendingReview为false')
    }
  } catch (error) {
    console.error('检查未通过申请失败:', error)
    hasPendingReview.value = false
  }
}

/** 查询楼宇列表 */
function getBuildingList() {
  listBuildingManage({}).then(response => {
    buildingList.value = response.rows
    // 创建楼宇ID到楼宇名称的映射
    buildingList.value.forEach(building => {
      buildingMap.value.set(building.id, building.buildingName)
    })
  })
}

  /** 根据楼宇ID获取楼宇名称 */
  function getBuildingName(buildingId) {
    return buildingMap.value.get(buildingId) || ''
  }

  /** 根据房间ID获取房间号 */
  function getRoomNo(roomId) {
    if (!roomId) return ''
    // 遍历房间列表找到对应的房间号
    const room = roomList.value.find(r => r.id === roomId)
    return room ? room.roomNo : ''
  }

// 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

// 表单重置
  function reset() {
    form.value = {
      id: null,
      userBuildingId: null,
      userRoomNo: null,
      userRoomId: null,
      userCarCode: null,
      userFaceFeature: null,
      faceImageUrl: null
    }
    proxy.resetForm("myRoomAndCarRef")
    submitButtonDisabled.value = false // 重置按钮状态
    submitButtonText.value = "确 定" // 重置按钮文字
  }

  /** 查询房间列表并构建映射关系 */
  function getRoomList() {
    // 获取房间列表
    listRoomManage({}).then(roomResponse => {
      roomList.value = roomResponse.rows

      // 创建房间号到房间ID的映射和房间ID到房间号的映射
      roomNoToIdMap.value.clear()
      roomIdToNoMap.value.clear()

      roomList.value.forEach(room => {
        roomNoToIdMap.value.set(room.roomNo, room.id)
        roomIdToNoMap.value.set(room.id, room.roomNo)
      })

      // 如果已有选中的楼宇，过滤房间列表
      if (form.value.userBuildingId) {
        filterRoomsByBuilding(form.value.userBuildingId)
      }
    }).catch(error => {
      console.error('获取房间列表失败:', error)
    })
  }

  /** 根据楼宇ID过滤房间列表 - 使用后端API获取未绑定的房间 */
  function filterRoomsByBuilding(buildingId) {
    if (!buildingId) {
      filteredRoomList.value = []
      form.value.userRoomNo = null
      return
    }


    // 使用新的后端API获取未绑定的房间列表
    getUnbindRoomsByBuildingId(buildingId).then(response => {
      if (response.code === 200) {
        filteredRoomList.value = response.data

        // 更新房间号到房间ID的映射
        filteredRoomList.value.forEach(room => {
          roomNoToIdMap.value.set(room.roomNo, room.id)
        })
      }
    })
  }

  /** 处理楼宇选择变化 */
  function handleBuildingChange(buildingId) {
    console.log('用户选择的楼宇ID:', buildingId)

    // 先清空当前过滤结果，显示加载状态
    filteredRoomList.value = []

    // 清空已选择的房间号
    form.value.userRoomNo = null

    // 执行过滤（这是一个异步操作）
    filterRoomsByBuilding(buildingId)
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

// 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 申请审核按钮操作 */
  function handleAdd() {
    reset()
    getRoomList()
    open.value = true
    title.value = "申请绑定车房信息"
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _id = row.id || ids.value
    getMyRoomAndCar(_id).then(response => {
      // 赋值原始数据
      form.value = response.data

      // 如果有房间ID，查找对应的房间号
      if (response.data.userRoomId) {
        const roomNo = roomIdToNoMap.value.get(response.data.userRoomId)
        if (roomNo) {
          form.value.userRoomNo = roomNo
        }
      }

      // 如果有选中的楼宇，过滤房间列表
      if (form.value.userBuildingId) {
        filterRoomsByBuilding(form.value.userBuildingId)
      }

      open.value = true
      title.value = "修改我的车房"
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["myRoomAndCarRef"].validate(valid => {
      if (valid) {
        // 禁用提交按钮并更改文字
        submitButtonDisabled.value = true
        submitButtonText.value = "提交中..."
        
        // 设置5秒后恢复按钮
        setTimeout(() => {
          submitButtonDisabled.value = false
          submitButtonText.value = "确 定"
        }, 5000)
        
        // 先检查是否已选择楼宇
        if (!form.value.userBuildingId) {
          proxy.$modal.msgError("请先选择楼宇名称")
          return
        }

        // 创建一个新对象，避免直接修改原始form对象
        const submitData = {...form.value}

        if (form.value.id != null) {
          // 修改操作，可能需要处理房间号到房间ID的转换
          if (form.value.userRoomNo) {
            const roomId = roomNoToIdMap.value.get(form.value.userRoomNo)
            if (roomId) {
              submitData.userRoomId = roomId
            } else {
              proxy.$modal.msgError("未找到对应的房间信息，请检查房间号是否正确")
              return
            }
          }
          updateMyRoomAndCar(submitData).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
            checkUserReviewStatus() // 重新检查未通过申请状态
          })
        } else {
          // 新增申请操作，需要将房间号转换为房间ID
          if (form.value.userRoomNo) {
            const roomId = roomNoToIdMap.value.get(form.value.userRoomNo)
            if (roomId) {
              submitData.userRoomId = roomId
            } else {
              proxy.$modal.msgError("未找到对应的房间信息，请检查房间号是否正确")
              return
            }
          }
          addSelfReview(submitData).then(response => {
            proxy.$modal.msgSuccess("申请提交成功，请等待审核")
            open.value = false
            getList()
            checkUserReviewStatus() // 重新检查未通过申请状态，确保状态正确更新
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal.confirm('是否确认删除我的车房编号为"' + _ids + '"的数据项？').then(function () {
      return delMyRoomAndCar(_ids)
    }).then(() => {
      getList()
      checkUserReviewStatus() // 重新检查未通过申请状态
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {
    })
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('myUserDetail/myRoomAndCar/export', {
      ...queryParams.value
    }, `myRoomAndCar_${new Date().getTime()}.xlsx`)
  }

  // 在组件挂载时初始化数据
  onMounted(async () => {
    try {
      // 直接调用现有的函数来获取数据
      await Promise.all([
        getBuildingList(),
        getRoomList()
      ])
      getList()
      await checkUserReviewStatus() // 使用新函数避免函数引用问题
    } catch (error) {
      console.error('初始化数据失败:', error)
    }
  })

</script>
